//
//  ZGQRCodeController.m
//  NewBee
//
//  Created by leergou on 16/8/21.
//  Copyright © 2016年 WhiteHouse. All rights reserved.
//

#import "ZGQRCodeController.h"
#import <AVFoundation/AVFoundation.h>
#import <QuartzCore/QuartzCore.h>

@interface ZGQRCodeController ()<AVCaptureMetadataOutputObjectsDelegate>

// 扫描框
@property (nonatomic, strong) UIView *scopeView;

// 扫描线
@property (nonatomic, strong) UIImageView *scanLineImageView;

// 提示框
@property (nonatomic,strong) UILabel *noticeLabel;

// 输入设备
@property (nonatomic,strong) AVCaptureInput *inputDevice;

// 输出设备
@property (nonatomic,strong) AVCaptureMetadataOutput *outputDevice;

// 对话
@property (nonatomic,strong) AVCaptureSession *session;


@end

@implementation ZGQRCodeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNav];
    [self setupUI];
    [self startScanQRCode];
    

}


#pragma mark - 按钮点击事件 -
- (void)backButtonClick{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 开始扫描 -
- (void)startScanQRCode{
    
    // 开始动画
    [self scanAnimation];
    
    // 1. 创建输入
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    self.inputDevice = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
    if (!self.inputDevice) {
        
        self.noticeLabel.text = @"没找到设备摄像头!";
        return;
    }
    
    
    // 2. 创建输出
    self.outputDevice = [AVCaptureMetadataOutput new];
    
    // 3. 创建session 关联输入和输出
    self.session = [AVCaptureSession new];
    if([self.session canAddInput:self.inputDevice]) {
        [self.session addInput:self.inputDevice];
    }
    if([self.session canAddOutput:self.outputDevice]) {
        [self.session addOutput:self.outputDevice];
    }
    
    // 3.1 设置输出的代理（注意：必须在添加到session）
    self.outputDevice.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
    [self.outputDevice setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // 4. 创建预览
    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    // 注意需要设置layer大小
    layer.frame = self.view.bounds;
    // 注意如果界面中有控件，控件会被覆盖，所以用insert插入最下面
    [self.view.layer insertSublayer:layer atIndex:0];
    
    // 5. 开始会话
    [self.session startRunning];
    
    
    
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate -
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
    for (AVMetadataMachineReadableCodeObject *obj in metadataObjects) {
        
        NSURL *url = [NSURL URLWithString:obj.stringValue];
        
        [ZGApplication openURL:url];
    }
}

#pragma mark - 设置界面 -
- (void)setupUI{
    self.view.backgroundColor = [UIColor grayColor];
    
    // 添加子控件
    [self.view addSubview:self.scopeView];
    [self.scopeView addSubview:self.scanLineImageView];
    [self.view addSubview:self.noticeLabel];
    
    
    // 添加约束
    [self.scopeView makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(100);
        make.width.height.equalTo(200);
    }];
    
    [self.scanLineImageView makeConstraints:^(MASConstraintMaker *make) {
        make.top.centerX.width.equalTo(self.scopeView);
        make.height.equalTo(3);
    }];
    
    [self.noticeLabel makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.scopeView.bottom);
        make.centerX.equalTo(self.view);
        
    }];
    
}

#pragma mark - 扫描动画 -
- (void)scanAnimation{
    // 创建动画
    CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"position.y"];
    
    // 设置动画属性
    basicAnimation.fromValue = @(0);
    basicAnimation.toValue = @(200);
    
    basicAnimation.repeatCount = FLT_MAX;//MAXFLOAT;
    basicAnimation.duration = 1.5;
    
    [self.scanLineImageView.layer addAnimation:basicAnimation forKey:nil];
    
}

#pragma mark - 设置导航条 -
- (void)setupNav{
    self.navigationItem.title = @"店铺二维码";
    
    [self.navigationController.navigationBar setBarTintColor:RGBCOLOR(249, 250, 253)];
   
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"v2_goback"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backButtonClick)];
}

#pragma mark - lazy -


- (UIView *)scopeView{
    if (!_scopeView) {
        _scopeView = [[UIView alloc] init];
        _scopeView.backgroundColor= [UIColor whiteColor];
    }
    return _scopeView;
}

- (UIImageView *)scanLineImageView{
    if (!_scanLineImageView) {
        _scanLineImageView = [[UIImageView alloc] init];
        [_scanLineImageView setImage:[UIImage imageNamed:@"yellowlight"]];
        _scanLineImageView.contentMode = UIViewContentModeScaleAspectFill;
        [_scanLineImageView sizeToFit];
    }
    return _scanLineImageView;
}

- (UILabel *)noticeLabel{
    if (!_noticeLabel) {
        _noticeLabel = [[UILabel alloc] init];
        _noticeLabel.text = @"将店铺二维码对准方块内既可收藏店铺";
        _noticeLabel.font = [UIFont systemFontOfSize:15];
        _noticeLabel.textColor = [UIColor blackColor];
        _noticeLabel.textAlignment = NSTextAlignmentCenter;
        [_noticeLabel sizeToFit];
    }
    return _noticeLabel;
}



@end




















